package com.alibaba.csp.sentinel.dashboard.rule.nacos.cluster;

import com.alibaba.csp.sentinel.dashboard.domain.cluster.ClusterGroupEntity;
import com.alibaba.csp.sentinel.dashboard.domain.cluster.config.ClusterClientConfig;
import com.alibaba.csp.sentinel.dashboard.domain.cluster.request.ClusterAppAssignMap;
import com.alibaba.csp.sentinel.dashboard.rule.DynamicRulePublisher;
import com.alibaba.csp.sentinel.dashboard.rule.nacos.NacosConfigUtil;
import com.alibaba.csp.sentinel.util.StringUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.alibaba.nacos.api.config.ConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component(value = "clusterClientConfigNacosPublisher")
public class ClusterClientConfigNacosPublisher implements DynamicRulePublisher<ClientConfig> {

    @Autowired
    private ConfigService configService;

    @Override
    public void publish(String app, ClientConfig config) throws Exception {
        if (null == config) {
            return;
        }
        String machineId = config.getMachineId();
        if (StringUtil.isBlank(machineId)) {
            return;
        }
        ClusterClientConfig clientConfig = new ClusterClientConfig();
        clientConfig.setRequestTimeout(config.getRequestTimeout());
        Map<String, ClusterClientConfig> configMap = new HashMap<>();
        String name = app + NacosConfigUtil.CLIENT_CONFIG_DATA_ID_POSTFIX;
        String data = configService.getConfig(name, NacosConfigUtil.GROUP_ID, 3000);
        if (StringUtil.isNotBlank(data)) {
            configMap = JSON.parseObject(data, new TypeReference<Map<String, ClusterClientConfig>>() {
            });
        }
        configMap.put(config.getMachineId(), clientConfig);
        configService.publishConfig(name, NacosConfigUtil.GROUP_ID, JSON.toJSONString(configMap));
    }
}
